public class HashBucket {

    static class Node {
        private int key;
        private int value;
        private Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    public Node[] array;
    public int usedSize;

    //默认的负载因子为0.75
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBucket() {
        this.array = new Node[10];
    }

    public void put(int key,int val) {
        Node node = new Node(key,val);
        int index = key % array.length;
        //遍历index位置下方的链表
        Node cur = array[index];
        Node tail = null;
        while(cur != null) {
            if(cur.key == key) {
                cur.value = val;
                return;
            }
            tail = cur;
            cur = cur.next;
        }
        //走到这说明cur == null 了，且没有这个Key,那么进行尾插法
        //tail.next = node;
        //头插法(如果尾插不行（我自己写的），就用头插)
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //计算负载因子
        if(lodeFactor() >= 0.75) {
            //扩容
            resize();
        }
    }


    //重新哈希原来的数据
    private void resize() {
        //2倍扩容
        Node[] tmpArray = new Node[array.length*2];
        //遍历原来的数组下标的每个链表
        for(int i = 0; i < array.length; i++) {
            //需要记录原链表的下一个位置
            Node cur = array[i];
            while(cur != null) {
                Node curNext = cur.next;
                //新数组的位置
                int index = cur.key % tmpArray.length;
                //采用头插法，放到新数组的位置
                //这里修改后，cur.next已经变了，所以前面需要记录下来cur.next的位置
                cur.next = tmpArray[index];
                tmpArray[index] = cur;
                cur = curNext;
            }
        }
        array = tmpArray;
    }

    private float lodeFactor() {
        return usedSize*1.0f / array.length;
    }

    /**
     * 通过key值返回value
     * @param key
     * @return
     */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
